package com.ifyyf.test.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author if
 * @Description: 调用原生ThreadPoolExecutor创建线程池
 * @Date 2021-11-07 下午 03:30
 */
public class MyPool {
    public static void main(String[] args) {
        System.out.println("CPU核心数量"+Runtime.getRuntime().availableProcessors());

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());//直接拒绝并且抛出异常
//                new ThreadPoolExecutor.CallerRunsPolicy());//谁调用的的，直接打回去让调用者执行
//                new ThreadPoolExecutor.DiscardPolicy());//拒绝、丢弃任务且不抛出异常
//                new ThreadPoolExecutor.DiscardOldestPolicy());//尝试争抢最老的线程且不抛出异常

        try{
            for(int i=1;i<=8;i++){
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"正在运行");
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            threadPoolExecutor.shutdown();
        }

    }
}
